package com.demo.task.ext

import android.util.Log
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.util.Date
import java.util.Locale
import kotlin.math.abs

private const val TAG = "DateExt"

/**
 * 扩展函数：判断 LocalDate 是否在给定的起止日期字符串表示的日期范围内
 */
fun isWithinDateRange(startDateStr: String, endDateStr: String): Boolean {
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
    val startDate = LocalDate.parse(startDateStr, formatter)
    val endDate = LocalDate.parse(endDateStr, formatter)
    val now = LocalDate.now()
    Log.i(TAG, "isWithinDateRange -> startDate:$startDate endDate:$endDate now:$now ")
    return now.isAfter(startDate.minusDays(1)) && now.isBefore(endDate.plusDays(1))
}

/**
 * 扩展函数：判断 LocalDateTime 是否在给定的起止时间字符串表示的时间范围内
 */
fun isWithinTimeRange(startTimeStr: String, endTimeStr: String): Boolean {
    val timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss")
    val startTime = LocalTime.parse(startTimeStr.filterMillisecond(), timeFormatter)
    val endTime = LocalTime.parse(endTimeStr.filterMillisecond(), timeFormatter)
    val currentTime = LocalDateTime.now().toLocalTime()
    Log.i(
        TAG,
        "isWithinTimeRange -> startTime:$startTime endTime:$endTime currentTime:$currentTime "
    )
    return currentTime.isAfter(startTime) && currentTime.isBefore(endTime)
}

fun String.filterMillisecond(): String {
    return substringBefore(".")
}

fun String.isMoreThanMinutes(time: Int): Boolean {
    return try {
        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
        // 将给定字符串时间转换为LocalDateTime对象
        val givenTime = LocalDateTime.parse(this, formatter)

        // 获取当前本地时间
        val currentTime = LocalDateTime.now()

        // 计算时间差（以分钟为单位）
        val minutesDifference = abs(ChronoUnit.MINUTES.between(givenTime, currentTime))

        // 判断是否大于五分钟
        minutesDifference > time
    } catch (e: Exception) {
        Log.e(TAG, "isMoreThanMinutes: ", e)
        false
    }
}

fun String?.toTime(): LocalTime? {
    return try {
        val formatter = DateTimeFormatter.ofPattern("HH:mm:ss")
        LocalTime.parse(this.orEmpty().substringBefore("."), formatter)
    } catch (e: Exception) {
        Log.e(TAG, "toTime: ", e)
        null
    }
}

fun currentTime(pattern: String = "yyyy-MM-dd HH:mm:ss"): String {
    return SimpleDateFormat(pattern, Locale.getDefault()).format(Date())
}